#include "header.h"
#include <string.h>


int char_to_int(char* exp);
char * int_to_char(int n, int base);

void deri_x(char* exp)
  {
    int i = 0;
    int expo_i = 0;
    char *temp = malloc(sizeof(char) * 5);
    char *expo = malloc(sizeof(char) * 5);
    temp[5] = '\0';
    expo[5] = '\0';
    if (exp[i] == 'x')
      {
	printf("Dérivé de %s : 1\n", exp);;
	return;
      }
    while(exp[i] != '\0' && exp[i] != 'x')
      {
	temp[i] = exp[i];
	i++;
      }
    if (exp[i] == '\0')
      {
	printf("Dérivé de %s : 0", exp);;
	return;
      }
    i++;
    if (exp[i] == '\0')
      {
	printf("Dérivé de %s : %s\n", exp, temp);;
	return;
      }
    i++;
    while(exp[i] != '\0')
      {
	expo[expo_i] = exp[i];
	i++;
	expo_i++;
      }
    i = char_to_int(temp);
    expo_i = char_to_int(expo);
    i *= expo_i;
    expo_i--;
    printf("Dérivé de %s : %ix^%i\n", exp, i, expo_i);;
  }



/*
  char* deri_poly(char* exp, char x)
  {
  char* tmp = malloc(sizeof(exp));
  int i = 0;
  while (exp[i] != '\0')
  {
  int exp_i = 0;
  while (exp[i] != '\0' && exp[i] = '-' && exp[i] != '+')
  {
  tmp[i] = exp[i];
  exp_i++;
  i++;
  }
  i++;
  }
  return exp_res;
  }*/

int char_to_int(char* exp)
{
  int i = 0;
  int res = 0;
  while(exp[i] != '\0' && exp[i] != ' ')
    {
      res = res*10 + (exp[i] % 48);
      i++;
    }
  return res;
}

char * int_to_char(int n, int base)
{
  char *r;
  int b = base;

  int l = 1;
  
  do
    {
      l++;
      b*=base;
    }
  while(n>=b);
  l--;

  r = malloc(sizeof(char)*(l+1));
  r[l+1]='\0';

  while(n>0)
    {
      r[l] = n % base;
      n -= r[l];
      r[l] += '0';
      n /= base;
      l--;
    }
  return r;
}

int main()
{
  deri_x("2x^8");
  return 0;
}
